﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.IO.Packaging;
using Microsoft.Office.Interop.Word;

namespace intelliSys.Management.Automation.Test
{
    public class WordGenerationEventArgs : EventArgs
    {
        public string Percentage
        {
            get;
            set;
        }
    }
    public class WordGenerationTask
    {
        public class PageSettingsViewModel
        {
            public string PaperSize
            {
                get;
                set;
            }
            public string Orientation
            {
                get;
                set;
            }
            public string Header
            {
                get;
                set;
            }
            public string Footer
            {
                get;
                set;
            }
        }
        public PageSettingsViewModel Settings
        {
            get;
            set;
        }
        public event EventHandler<WordGenerationEventArgs> ReportProgress;
        public Exception exception;
        Random randomNum = new Random(DateTime.Now.Millisecond);
        public void MergeFile(intelliPaper.Model.Question[] Questions)
        {
            Application wordApp = new Application();
            try
            {
                var Root = wordApp.Documents.Add();
                for (int i = 0; i < Questions.Length; i++)
                {
                    intelliPaper.Model.Question Attached = Questions[i];
                    if (ReportProgress != null)
                    {
                        ReportProgress(this, new WordGenerationEventArgs() { Percentage = ((double)i / (double)Questions.Length).ToString().PadLeft(2, '0').Substring(0, 2) });
                    }
                    XmlDocument xmlDoc = new XmlDocument() { InnerXml = Questions[i].QuestionBody };
                    var node = xmlDoc.ChildNodes[2];
                    var package = Package.Open(Directory.GetCurrentDirectory() + "\\paperTemp.docx", FileMode.Create, FileAccess.ReadWrite);
                    foreach (XmlNode part in node.ChildNodes)
                    {
                        var ignoreNodes = part.Attributes["pkg:name"].Value;
                        var pt = package.CreatePart(new System.Uri(part.Attributes["pkg:name"].Value, UriKind.Relative), part.Attributes["pkg:contentType"].Value);
                        XmlDocument xmltempDoc = new XmlDocument();
                        try
                        {
                            xmltempDoc.InnerXml = part.ChildNodes[0].InnerXml;
                            xmltempDoc.Save(pt.GetStream(FileMode.Create, FileAccess.Write));
                        }
                        catch
                        {
                            var x = System.Convert.FromBase64String(part.InnerText);
                            pt.GetStream(FileMode.Create, FileAccess.Write).Write(x, 0, x.Length);
                        }
                    }
                    package.Flush();
                    package.Close();
                    Root.Paragraphs.Add();
                    var current = wordApp.Documents.Open(Directory.GetCurrentDirectory() + "\\paperTemp.docx");
                    current.Range().Copy();
                    var NewPara = Root.Paragraphs.Last;
                    var lstParaIdx = Root.Paragraphs.Count;
                    NewPara.Range.Paste();
                    Root.Paragraphs[lstParaIdx].Range.ListFormat.ApplyNumberDefault();
                    Root.Paragraphs[lstParaIdx].LeftIndent = 0;
                    int totalCount = Attached.TrueAnswers.Count + Attached.ErrorAnswers.Count;
                    int m = 0, n = 0;
                    bool prefix = Attached.QuestionType == "选择题";
                    Random randomNum = new Random();
                    bool Boldflag = false;
                    for (int x = 0; x < totalCount; x++)
                    {
                        Boldflag = false;
                        Root.Paragraphs.Add();
                        var para1 = Root.Paragraphs.Last;
                        //还有错误答案则放错误答案
                        var rand = randomNum.Next() % 2;
                        if (rand == 0)
                        {
                            //  bkup.Font = new WORD.Font() { Bold = 0 };
                            if (m < Attached.ErrorAnswers.Count)
                            {
                                if (prefix)
                                {
                                    para1.Range.InsertAfter(Convert.ToChar('A' + m + n) + "." + Attached.ErrorAnswers[m]);
                                }
                                else
                                {
                                    para1.Range.InsertAfter(Attached.ErrorAnswers[m]);
                                }
                                //   bkup.Font = new WORD.Font() { Bold = 0 };
                                m++;
                            }
                            else
                            {
                                Boldflag = true;
                                // bkup.Font = new WORD.Font() { Bold = 1 };
                                if (prefix)
                                {
                                    para1.Range.InsertAfter(Convert.ToChar('A' + m + n) + "." + Attached.TrueAnswers[n]);
                                }
                                else
                                {
                                    para1.Range.InsertAfter(Attached.TrueAnswers[n]);
                                }
                                //para1.Range.Text += "\r";
                                n++;
                            }
                        }
                        //还有正确答案则放正确答案
                        else
                        {
                            if (n < Attached.TrueAnswers.Count)
                            {
                                //  bkup.Font = new WORD.Font() { Bold = 1 };
                                if (prefix)
                                {
                                    para1.Range.InsertAfter(Convert.ToChar('A' + m + n) + "." + Attached.TrueAnswers[n]);
                                }
                                else
                                {
                                    para1.Range.InsertAfter(Attached.TrueAnswers[n]);
                                }
                                Boldflag = true;
                                //para1.Range.Text += "\r";
                                n++;
                            }
                            else
                            {
                                //    bkup.Font = new WORD.Font() { Bold = 0 };
                                if (prefix)
                                {
                                    para1.Range.InsertAfter(Convert.ToChar('A' + m + n) + "." + Attached.ErrorAnswers[m]);
                                }
                                else
                                {
                                    para1.Range.InsertAfter(Attached.ErrorAnswers[m]);
                                }
                                Boldflag = false;
                                //  para1.Range.Text += "\r";
                                m++;
                            }
                        }
                        Root.Paragraphs.Add(para1.Range);

                        Root.Paragraphs.Last.Range.ListFormat.RemoveNumbers();
                        Root.Paragraphs.Last.Range.Font.Bold = 0;
                        if (Boldflag)
                        {
                            Root.Paragraphs.Last.Range.Font.Bold = 1;
                        }
                    }
                    current.Close(WdSaveOptions.wdDoNotSaveChanges);
                }
                Root.PageSetup.PaperSize = Settings.PaperSize == "A4" ? WdPaperSize.wdPaperA4 : WdPaperSize.wdPaperA3;
                Root.PageSetup.Orientation = Settings.Orientation == "景色" ? WdOrientation.wdOrientLandscape : WdOrientation.wdOrientPortrait;
                Root.Sections.First.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = Settings.Header;
                Root.Sections.First.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paragraphs.Add();
                var para = Root.Sections.First.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paragraphs.Add();
                var rg = para.Range;
                rg.Text = "草稿区";
                rg.Font.Size = 24;
                rg.Bold = 1;
                para.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                if (Settings.Footer == "_USEDEFAULT_")
                {
                    Root.Sections.First.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(WdPageNumberAlignment.wdAlignPageNumberCenter, true);
                }
                else
                {
                    Root.Sections.First.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = Settings.Footer;
                }
                wordApp.Visible = true;
                wordApp.Quit(WdSaveOptions.wdPromptToSaveChanges);
                File.Delete((Directory.GetCurrentDirectory() + "\\paperTemp.docx"));
            }
            catch (Exception ex)
            {
                exception = ex;
                try
                {
                    wordApp.Quit(WdSaveOptions.wdDoNotSaveChanges);
                }
                catch
                {
                    exception = new ApplicationException("上次生成的试卷文档未关闭，关闭该文档再试一次。");
                }
            }
        }
        void adjustIndent(Paragraph orig, Paragraph drv)
        {
        }
    }
}
